import type { StyleTagOptions } from './index'
import { APP_CONFIG, logger } from '../../types/constants'
import { SYMBOLS } from '../../types/interfaces'
import { ToolKit } from '../utils/toolkit'

/**
 * 样式注入器基类
 */
export abstract class StyleBaseInjector {
  abstract readonly name: string
  abstract readonly styleTags: any

  /**
   * 销毁注入器
   */
  destroy(): void {}

  /**
   * 创建样式标签
   */
  abstract createStyleTag(
    id: string,
    content: string,
    options?: StyleTagOptions
  ): HTMLStyleElement | null

  /**
   * 移除样式标签
   */
  removeStyleTag(id: string): boolean {
    const style = this.getStyleTag(id)
    const isArray = Array.isArray(style)

    if (!style || (isArray && style.length === 0)) {
      logger.warn(`[${this.name}] 样式标签不存在: id='${id}'`)
      return false
    }

    if (isArray) {
      style.forEach(style => style.remove())
    }
    else {
      style.remove()
    }

    this.styleTags.delete(id)
    logger.success(`[${this.name}] ${SYMBOLS.UI.BOOKMARK} 样式标签已移除: id='${id}'`)
    return true
  }

  /**
   * 注入样式到目标元素
   */
  abstract injectStyle(
    style: HTMLStyleElement,
    options: StyleTagOptions
  ): boolean

  /**
   * 更新样式标签内容
   */
  abstract updateStyle(
    id: string,
    content: string,
    options?: StyleTagOptions
  ): boolean

  /**
   * 获取样式标签
   */
  abstract getStyleTag(id: string): HTMLStyleElement[] | HTMLStyleElement | null

  /**
   * 生成样式 ID
   */
  abstract generateStyleId(id: string): string

  /**
   * 检查样式内容是否有效
   */
  protected checkContentValidity(id: string, content: string, onlyCreate: boolean, allowEmpty: boolean): boolean {
    if (!content && !allowEmpty && !onlyCreate) {
      logger.warn(`[${this.name}] 样式内容为空且未启用空内容创建，跳过样式创建：id='${id}'`)
      return false
    }

    return true
  }

  /**
   * 处理样式内容
   */
  processStyleContent(content: string): string {
    if (APP_CONFIG.minifyCSS === true)
      content = ToolKit.ui.style.minifyCSS(content)

    return content
  }
}
